package org.jeecg.modules.demo.yxtraderdata.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.utils.HttpClientUtil;
import org.jeecg.modules.demo.yxpingdata.entity.YxPinpData;
import org.jeecg.modules.demo.yxtraderdata.entity.YxTraderData;
import org.jeecg.modules.demo.yxtraderdata.service.IYxTraderDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: yx_trader_data
 * @Author: jeecg-boot
 * @Date:   2022-11-10
 * @Version: V1.0
 */
@Api(tags="yx_trader_data")
@RestController
@RequestMapping("/yxtraderdata/yxTraderData")
@Slf4j
public class YxTraderDataController extends JeecgController<YxTraderData, IYxTraderDataService> {
	@Autowired
	private IYxTraderDataService yxTraderDataService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Value(value = "${reloadDataUrl}")
	private String reloadDataUrl;
	/**
	 * 分页列表查询
	 *
	 * @param yxTraderData
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "交易商管理-分页列表查询")
	@ApiOperation(value="交易商管理-分页列表查询", notes="交易商管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(YxTraderData yxTraderData,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<YxTraderData> queryWrapper = QueryGenerator.initQueryWrapper(yxTraderData, req.getParameterMap());
			Page<YxTraderData> page = new Page<YxTraderData>(pageNo, pageSize);
			IPage<YxTraderData> pageList = yxTraderDataService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *   添加
	 *
	 * @param yxTraderData
	 * @return
	 */
	@AutoLog(value = "交易商管理-添加")
	@ApiOperation(value="交易商管理-添加", notes="交易商管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody YxTraderData yxTraderData,HttpServletRequest req) {
		try{
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> strings = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
			if(strings.contains("admin")||strings.contains("administrator")){
				String tenantId = req.getHeader("tenant-id");
				yxTraderData.setCreateTime(new Date());
				yxTraderData.setAddtime(new Date());
				yxTraderData.setTenantId(Integer.parseInt(tenantId));
				yxTraderData.setTraderauthstatus("0");
				yxTraderData.setAddmethod(0);
				yxTraderData.setDelFlag(CommonConstant.DEL_FLAG_0);
				yxTraderDataService.save(yxTraderData);
				return Result.OK("添加成功！");
			}else{
				return  Result.error(500,"您无此权限，请联系管理员！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	@AutoLog(value = "交易商管理-通过认证")
	@ApiOperation(value="交易商管理-通过认证", notes="交易商管理-通过认证")
	@PostMapping(value = "/checkTrader")
	public Result<?> checkTrader(@RequestBody YxTraderData yxTraderData) {
		try{
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> strings = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
			if(strings.contains("admin")||strings.contains("administrator")){
				yxTraderData.setTraderauthstatus("3");
				yxTraderDataService.updateById(yxTraderData);
				return Result.OK("通过认证成功！");
			}else{
				return  Result.error(500,"您无此权限，请联系管理员！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	@AutoLog(value = "交易商管理-取消认证")
	@ApiOperation(value="交易商管理-取消认证", notes="交易商管理-取消认证")
	@PostMapping(value = "/unCheckTrader")
	public Result<?> unCheckTrader(@RequestBody YxTraderData yxTraderData) {
		try{
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> strings = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
			if(strings.contains("admin")||strings.contains("administrator")){
				yxTraderData.setTraderauthstatus("0");
				yxTraderDataService.updateById(yxTraderData);
				return Result.OK("取消认证成功！");
			}else{
				return  Result.error(500,"您无此权限，请联系管理员！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}
	 /**
	  *  同步
	  *
	  * @return
	  */
	 @AutoLog(value = "交易商管理-同步")
	 @ApiOperation(value="交易商管理-同步", notes="交易商管理-同步")
	 @PostMapping(value = "/reloadData")
	 public Result<?> reloadData(HttpServletRequest req) {
		try{
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> strings = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
			if(strings.contains("admin")||strings.contains("administrator")){
				String tenantId = req.getHeader("tenant-id");
				String json = HttpClientUtil.doGet(reloadDataUrl);
				JSONObject jsonObject = (JSONObject) JSONObject.parse(json);
				String JsonStr  = jsonObject.get("data").toString();
				List<YxTraderData> traderDataList = JSONArray.parseArray(JsonStr,YxTraderData.class);
				List<String> ids  = yxTraderDataService.getList();
				if(!ids.isEmpty()){
					yxTraderDataService.removeByIds(ids);
				}
				for (YxTraderData yxTraderData : traderDataList) {
					yxTraderData.setId(null);
					yxTraderData.setCreateTime(yxTraderData.getAddtime());
					yxTraderData.setTenantId(Integer.parseInt(tenantId));
					yxTraderData.setAddmethod(1);
					yxTraderDataService.save(yxTraderData);

				}
				return Result.OK("同步数据成功!");
			}else{
				return  Result.error(500,"您无此权限，请联系管理员！");
			}

		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	 }


	/**
	 *  编辑
	 *
	 * @param yxTraderData
	 * @return
	 */
	@AutoLog(value = "交易商管理-编辑")
	@ApiOperation(value="交易商管理-编辑", notes="交易商管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody YxTraderData yxTraderData) {
		try{
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> strings = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
			if(strings.contains("admin")||strings.contains("administrator")){
				yxTraderDataService.updateById(yxTraderData);
				return Result.OK("编辑成功!");
			}else{
				return  Result.error(500,"您无此权限，请联系管理员！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "交易商管理-通过id删除")
	@ApiOperation(value="交易商管理-通过id删除", notes="交易商管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			// 获取登录用户信息
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> strings = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
			if(strings.contains("admin")||strings.contains("administrator")){
				YxTraderData yxTraderData = yxTraderDataService.getById(id);
				if(yxTraderData.getAddmethod()==1){
					return Result.error(500,"该交易商信息为同步数据,无法删除!");
				}
				if(Integer.parseInt(yxTraderData.getTraderauthstatus())==3){
					return Result.error(500,"该交易商信息已认证,无法删除!");
				}
				yxTraderDataService.removeById(id);
				return Result.OK("删除成功!");
			}else{
				return  Result.error(500,"您无此权限，请联系管理员！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	@GetMapping("/getTraderData")
	public Result getTraderData() {
		List<YxTraderData> logicDeletedTraderDataList = yxTraderDataService.getTraderData();
		return Result.ok(logicDeletedTraderDataList);
	}


	@RequestMapping(value = "/revertLogicDeletedTraderData", method = RequestMethod.PUT)
	public Result revertLogicDeletedTraderData(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
		// 获取登录用户信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<String> strings = sysBaseAPI.getRolesByUsername(sysUser.getUsername());
		if(strings.contains("admin")||strings.contains("administrator")){
			String tradeDataIds = jsonObject.getString("tradeDataIds");
			if (StringUtils.isNotBlank(tradeDataIds)) {
				yxTraderDataService.revertLogicDeletedTraderData(Arrays.asList(tradeDataIds.split(",")));
			}
			return Result.ok("还原成功");
		}else{
			return  Result.error(500,"您无此权限，请联系管理员！");
		}
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "交易商管理-批量删除")
	@ApiOperation(value="交易商管理-批量删除", notes="交易商管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.yxTraderDataService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "交易商管理-通过id查询")
	@ApiOperation(value="交易商管理-通过id查询", notes="交易商管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		YxTraderData yxTraderData = yxTraderDataService.getById(id);
		if(yxTraderData==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(yxTraderData);
	}

	@PostMapping(value = "/getTraderByStr")
	public String getTraderByStr(@RequestParam(name="str",required=true)String str){
		Gson gson = new Gson();
		Map map = new HashMap();
		try{
			if(!StringUtils.isNotBlank(str)){
				map.put("code",300);
				map.put("message","参数不能为空！");
				String json = gson.toJson(map);
				return json;
			}
			QueryWrapper<YxTraderData> queryWrapper = new QueryWrapper<>();
			queryWrapper.like(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(str),"FULLNAME", str);
			queryWrapper.eq("TRADERAUTHSTATUS",3);
			List<YxTraderData> mapList = yxTraderDataService.list(queryWrapper);
			map.put("code",200);
			map.put("message","查询成功！");
			map.put("data",mapList);
			String json = gson.toJson(map);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",500);
			map.put("message","系统错误！");
			String json = gson.toJson(map);
			return json;
		}
	}

    /**
    * 导出excel
    *
    * @param request
    * @param yxTraderData
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YxTraderData yxTraderData) {
        return super.exportXls(request, yxTraderData, YxTraderData.class, "yx_trader_data");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, YxTraderData.class);
    }

}
